package com.piggy.settlement.sdk.util.v2;

import cn.hutool.core.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author ：daxia
 * @description：计算AES签名的工具类
 * @modified By：
 * @version: 1.0$
 */
public class PiggyOpenBasicsAesUtil {

    public static String produceAesData(String secret, String ivStr, Object params) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            String jsonParam = PiggyOpenBasicsVerifyUtil.buildMapToSign(params);
            byte[] raw = secret.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(jsonParam.getBytes("UTF-8"));
            String enString = Base64.encode(encrypted);
            return URLEncoder.encode(enString);
        } catch (Exception e) {
            System.out.println("AES加密异常" + e);
        }
        return "";
    }

    public static String analysisAesDataDev(String secret, String ivStr, String aesData) {
        try {
            byte[] raw = secret.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            String tempStr = URLDecoder.decode(aesData);
            byte[] encrypted1 = Base64.decode(tempStr);
            byte[] original = cipher.doFinal(encrypted1);
            String jsonParam = new String(original, "UTF-8");
            return jsonParam;
        } catch (Exception e) {
            System.out.println("AES解密异常" + e);
        }
        return "";
    }
}
